package com.smartcruise.util.network;

import android.util.Log;

import com.smartcruise.util.Key;
import com.smartcruise.util.SPUtils;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by FengChaoQun
 * on 2018/3/26 0026
 */

public class ParamsInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (request.method().equals("POST")) {
            if (request.body() instanceof FormBody) {
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                FormBody formBody = (FormBody) request.body();

                //把原来的参数添加到新的构造器，（因为没找到直接添加，所以就new新的）
                for (int i = 0; i < formBody.size(); i++) {
                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                }

                formBody = bodyBuilder
                        .addEncoded(Key.token, SPUtils.getLastToken())
                        .build();

                Log.d("ParamsInterceptor", "add ok");

                request = request.newBuilder().post(formBody).build();
            } else if (request.body() instanceof MultipartBody) {
                MultipartBody multipartBody = (MultipartBody) request.body();
                MultipartBody.Builder builder = new MultipartBody.Builder();
                builder.setType(MultipartBody.FORM);
                //添加原请求体
                for (int i = 0; i < multipartBody.size(); i++) {
                    builder.addPart(multipartBody.part(i));
                }
                builder.addFormDataPart(Key.token, SPUtils.getLastToken());
                multipartBody = builder.build();
                request = request.newBuilder().post(multipartBody).build();
            }
        }
        return chain.proceed(request);
    }
}